﻿using AutoTest.Business.IServices;
using AutoTest.Business.IServices.Common;
using AutoTest.Business.IServices.Pay;
using AutoTest.Business.Options;
using AutoTest.Business.Vo.Order;
using AutoTest.Common;
using AutoTest.Common.Extension;
using AutoTest.Domain;
using AutoTest.Domain.Entities;
using AutoTest.Domain.Enums;
using AutoTest.Framework.Exceptions;
using AutoTest.Framework.Ioc;
using SKIT.FlurlHttpClient.Wechat.TenpayV3;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Models;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Settings;
using SqlSugar;

namespace AutoTest.Business.Services.Pay
{
    /// <summary>
    /// 微信支付服务
    /// </summary>
    public class WechatPayService(ISqlSugarClient db
        , IOrderLogService orderlogService
        , ISettingService settingService
        ) : IPayService, IScoped
    {
        private readonly ISqlSugarClient _db = db;
        private readonly IOrderLogService _orderlogService = orderlogService;

        private readonly WechatAppOption _wechatOption = settingService.GetSettingOptionAsync<WechatAppOption>(AppConsts.APPSETTING_WECHAT_APP).GetAwaiter().GetResult();

        /// <summary>
        /// 微信支付统一下单
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        public async Task<CreateOrderResultVo<IDictionary<string, string>>> CreateOrderAsync(Order order)
        {
            if (order.OpenId.IsEmpty())
            {
                var openInfo = await _db.Queryable<OpenInfo>().Where(c => c.UserId == order.UserId && c.Platform == "Wechat").FirstAsync();
                order.OpenId = openInfo?.OpenId ?? "";
            }
          
            string returmMsg = string.Empty;
            int price = order.PayableAmount;
            if (order.IsDebug) price = 1;

            order.IsProfitSharing = _wechatOption.IsProfitSharing;

            var client = GetWechatPayClient();

            var response = await client.ExecuteCreatePayTransactionJsapiAsync(new CreatePayTransactionJsapiRequest() {
                Amount = new CreatePayTransactionJsapiRequest.Types.Amount() { Total = price },
                AppId = _wechatOption.WechatAppId,
                Attachment = order.GoodsId.ToString(),
                Description = order.GoodsName,
                Detail = null,
                ExpireTime = DateTimeOffset.Now.AddMinutes(15),
                GoodsTag = null,
                IsSupportFapiao = false,
                MerchantId = null,
                NotifyUrl = _wechatOption.WechatPayNotifyUrl,
                OutTradeNumber = order.OrderId,
                Payer = new CreatePayTransactionJsapiRequest.Types.Payer() {  OpenId = order.OpenId, },
                Scene = new CreatePayTransactionJsapiRequest.Types.Scene() { ClientIp = order.Ip,DeviceId = "",Store = null },
                Settlement = new CreatePayTransactionJsapiRequest.Types.Settlement() { IsProfitSharing = order.IsProfitSharing }
            });

            if (response.IsSuccessful())
            {
                await _orderlogService.AddOrderLogAsync(order.OrderId, "微信统一下单成功", order.UserId,response.ToJson());
                var jsApiParams = client.GenerateParametersForJsapiPayRequest(_wechatOption.WechatAppId, response.PrepayId);
                return new CreateOrderResultVo<IDictionary<string,string>>()
                {
                    PayType = EnumPayType.WxJs,
                    Id = order.Id,
                    OrderId = order.OrderId,
                    ResultData = jsApiParams, //response
                };
            }
            else
            {
                await _orderlogService.AddOrderLogAsync(order.OrderId, $"微信统一下单失败，失败原因：{response.ErrorCode}|{response.ErrorMessage}", order.UserId, response.ToJson());
                throw new BusinessException($"{response.ErrorCode}|{response.ErrorMessage}");
            }
         
        }
        

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        private WechatTenpayClient GetWechatPayClient()
        {
            string privatekey = File.ReadAllText(_wechatOption.WechatCertificatePrivateKeyPath);
            string merchantNo = _wechatOption.WechatMerchantNo; 
            string serialNo = _wechatOption.WechatCertificateSerialNumber;
            string v3secret = _wechatOption.WechatV3Secret;

            if (privatekey.IsEmpty() || merchantNo.IsEmpty() ||  v3secret.IsEmpty()) throw new BusinessException("商户配置不正确");

            var manager = new InMemoryCertificateManager();
            var options = new WechatTenpayClientOptions()
            {
                MerchantId = merchantNo,
                MerchantV3Secret = v3secret,
                MerchantCertificateSerialNumber = serialNo,
                MerchantCertificatePrivateKey = privatekey,
                PlatformCertificateManager = manager // 平台证书管理器的具体用法请参阅下文的基础用法与加密、验签有关的章节
            };
            var client = WechatTenpayClientBuilder.Create(options).Build();
            return client;
        }
    }
}
